package com.ruoyi.client.service.impl;

import com.ruoyi.client.mapper.ClientCartMapper;
import com.ruoyi.client.pojo.form.BatchIdsForm;
import com.ruoyi.client.pojo.form.CartAddForm;
import com.ruoyi.client.pojo.form.CartUpdateForm;
import com.ruoyi.client.pojo.vo.CartVo;
import com.ruoyi.client.service.ClientCartService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.myshop.domain.Cart;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * 购物车Service实现类（已移除库存相关逻辑）
 * 实现购物车核心业务操作，与接口 ClientCartService 一一对应
 */
@Service
public class ClientCartServiceImpl implements ClientCartService {

    @Resource
    private ClientCartMapper clientCartMapper;

    @Override
    public Boolean add(CartAddForm form) {
        // 校验参数
        Assert.notNull(form.getGoodsId(), "商品ID不能为空");
        Assert.isTrue(form.getCount() != null && form.getCount() > 0, "商品数量必须大于0");

        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 检查商品是否已在购物车中
        Cart existCart = clientCartMapper.selectByUserIdAndGoodsId(userId, form.getGoodsId());

        if (existCart != null) {
            // 已存在则更新数量（直接累加，无库存限制）
            Long newCount = existCart.getCount() + form.getCount();
            // 调用原子更新方法
            return clientCartMapper.updateCount(existCart.getId(), newCount) > 0;
        } else {
            // 不存在则新增
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setGoodsId(form.getGoodsId());
            cart.setCount(form.getCount());
            cart.setIsChecked(1);
            return clientCartMapper.insert(cart) > 0;
        }
    }

    @Override
    public Boolean deleteById(Long id) {
        Assert.notNull(id, "购物车记录ID不能为空");

        Long userId = SecurityUtils.getUserId();
        // 校验归属权
        Cart cart = clientCartMapper.selectById(id);
        if (cart == null || !cart.getUserId().equals(userId)) {
            throw new ServiceException("无权操作该购物车记录");
        }

        return clientCartMapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public Boolean deleteBatch(BatchIdsForm form) {
        Assert.notNull(form.getIds(), "ID数组不能为空");
        for (Long id : form.getIds()) {
            Assert.notNull(id, "ID数组中不能包含null元素");
        }

        Long userId = SecurityUtils.getUserId();
        List<Long> idList = form.getIds();
        // 校验批量归属权
        List<Cart> cartList = clientCartMapper.selectByIds(idList);
        if (cartList.size() != idList.size()) {
            throw new ServiceException("存在无权操作的购物车记录");
        }
        for (Cart cart : cartList) {
            if (!cart.getUserId().equals(userId)) {
                throw new ServiceException("存在无权操作的购物车记录");
            }
        }

        return clientCartMapper.deleteBatch(idList.toArray(new Long[0])) > 0;
    }

    @Override
    public Boolean deleteAllByMy() {
        Long userId = SecurityUtils.getUserId();
        return clientCartMapper.deleteByUserId(userId) > 0;
    }

    @Override
    public Boolean update(CartUpdateForm form) {
        Assert.notNull(form.getId(), "购物车记录ID不能为空");

        Long userId = SecurityUtils.getUserId();
        // 校验归属权
        Cart cart = clientCartMapper.selectById(form.getId());
        if (cart == null || !cart.getUserId().equals(userId)) {
            throw new ServiceException("无权操作该购物车记录");
        }

        // 处理数量更新（仅校验数量>0，无库存限制）
        if (form.getCount() != null) {
            Assert.isTrue(form.getCount() > 0, "商品数量必须大于0");
        }

        // 转换为Cart对象更新
        Cart updateCart = new Cart();
        updateCart.setId(form.getId());
        updateCart.setCount(form.getCount());
        updateCart.setIsChecked(form.getIsChecked());
        return clientCartMapper.update(updateCart) > 0;
    }

    @Override
    public Boolean updateIsCheckedAll(Integer isChecked) {
        Assert.isTrue(isChecked == 0 || isChecked == 1, "勾选状态只能是0或1");

        Long userId = SecurityUtils.getUserId();
        return clientCartMapper.updateIsCheckedAllByUserId(userId, isChecked) > 0;
    }

    @Override
    public List<CartVo> listByMy() {
        Long userId = SecurityUtils.getUserId();
        return clientCartMapper.listByUserId(userId);
    }

    @Override
    public List<CartVo> listIsCheckedByMy() {
        Long userId = SecurityUtils.getUserId();
        return clientCartMapper.listIsCheckedByUserId(userId);
    }
}